package com.ticker.national.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.ticker.national.util.Log;

public class PersonInfoDB extends SQLiteOpenHelper {
	
	private final String TAG = "PersonInfoDB";
	private static final String DATABASE_NAME = "person_info.db";
	
	public static final String _ID = "_id";
	public static final String NAME = "name";
	public static final String AGE = "age";
	
	private static int DATABASE_VERSION = 1;

	public PersonInfoDB(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		Log.d(TAG, "PersonInfoDB()");
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.d(TAG, "onCreate()");
		
		Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='" + DATABASE_NAME + "'", null);
		
		if(cursor.getCount() == 0) {
			createTables(db);
		}
		cursor.close();
	}

	private void createTables(SQLiteDatabase db) {
		Log.d(TAG, "createTables()");
		
//		db.execSQL("CREATE TABLE " + DB_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, name char not null, age REAL not null);");
		
		for (String tableName : SchemeCollection.getQueriesCreateTable().keySet()) {
			String curQuery = SchemeCollection.getQueriesCreateTable().get(tableName);

			Log.d(TAG, "curQuery: " + curQuery);
			Log.d(TAG, "Table Create : " + tableName);
			db.execSQL(curQuery);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i(TAG, "onUpgrade()");
        Log.i(TAG, "Upgrading personInfo database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
        
        dropTables(db);
        onCreate(db);
	}

	private void dropTables(SQLiteDatabase db) {
		Log.e(TAG, "dropTables()");
		
        for (String tableName : SchemeCollection.getQueriesDropTable().keySet()) {
            String curQuery = SchemeCollection.getQueriesDropTable().get(tableName);
            
            Log.d(TAG, "curQuery: " + curQuery);
            Log.d(TAG, "Table drop : " + tableName);
            db.execSQL(curQuery);
        }
	}
}
